package org.simon.myauctioneer.dao;

import java.sql.*;

import org.simon.myauctioneer.dto.User;

public class UserDAO implements UserDAOI {

	private PreparedStatement saveStmt;
	private PreparedStatement loadStmt;

	public UserDAO(String url, String user, String pw) {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			Connection con = DriverManager.getConnection(url, user, pw);
			saveStmt = con
					.prepareStatement("INSERT INTO customer(name, address, phone, email, password) "
							+ "VALUES (?, ?, ?, ?, ?)");
			loadStmt = con.prepareStatement("SELECT * FROM customer "
					+ "WHERE email = ?");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void saveUser(User u) {
		try {
			saveStmt.setString(1, u.getName());
			saveStmt.setString(2, u.getAddress());
			saveStmt.setString(3, u.getPhone());
			saveStmt.setString(4, u.getEmail());
			saveStmt.setString(5, u.getPassword());
			saveStmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public User loadUser(String email) {
		User u = new User();
		try {
			loadStmt.setString(1, email);
			ResultSet result = loadStmt.executeQuery();
			if (!result.next())
				return null;

			u.setUserId(result.getInt("customer_id"));
			u.setName(result.getString("name"));
			u.setAddress(result.getString("address"));
			u.setPhone(result.getString("phone"));
			u.setEmail(result.getString("email"));
			u.setPassword(result.getString("password"));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return u;
	}

}
